package com.blank.white.common.config;


import com.blank.white.common.enums.CacheTypeEnum;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class CaffeineCacheConfig {

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCachePlus> caffeineCaches = new ArrayList<>();

        for (CacheTypeEnum cacheType : CacheTypeEnum.values()) {
            caffeineCaches.add(new CaffeineCachePlus(cacheType.getName(), Caffeine.newBuilder()
                    .expireAfterWrite(cacheType.getExpires(), TimeUnit.SECONDS)
                    .initialCapacity(cacheType.getInitSize())
                    .maximumSize(cacheType.getMaxSize()).build(new CacheLoader<>() {

                        @Override
                        public @Nullable Object load(@NonNull Object s) throws Exception {
                            return null;
                        }
                    })));
        }

        cacheManager.setCaches(caffeineCaches);
        return cacheManager;
    }

    @Bean("CACHE_DEFAULT")
    public LoadingCache defaultCache(CacheManager cacheManager) {
        LoadingCache defaultCache = ((CaffeineCachePlus) cacheManager.getCache("CACHE_DEFAULT")).getLoadingCache();
        return defaultCache;
    }

}

